package com.stu.day18;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁:
 * 写写互斥
 * 读写互斥
 * 读读共享
 * 为什么读操作本身就应该是可以让多个线程同时访问的,但是还需要加一个读锁.
 * 目的是为了防止一个线程在修改,另外一个线程在读,写线程在修改的同时,读线程可能读取到的是修改之前/过程中的一个脏的数据.
 * 读写锁 -> 适合读多写少的场景
 *  ReadWriteLock rwLock = new ReentrantReadWriteLock();
 *  Lock readLock = rwLock.readLock();
 *  Lock writeLock = rwLock.writeLock();
 * @author zy
 * @date 2025/2/19 09:45
 */
public class ReadWriteDemo {
    //线程非安全的
    private volatile Map<String,String> map = new HashMap<>();

    //读写锁的对象
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    //写
    public void put(String key,String value){
        //申请一个写锁
        try{
            lock.writeLock().lock();  // WriteLock implements Lock
            System.out.println(Thread.currentThread().getName()+"正在写入...");
            map.put(key,value);
            TimeUnit.SECONDS.sleep(2);
            System.out.println(Thread.currentThread().getName()+"写入成功...");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.writeLock().unlock();
        }
    }

    //读
    public void get(String key){
        //申请一个写锁
        try{
            lock.readLock().lock();
            System.out.println(Thread.currentThread().getName()+"正在读取===");
            TimeUnit.SECONDS.sleep(2);
            String value = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读去成功:"+value);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.readLock().unlock();
        }
    }
}
class ReadWriteDemoTest{
    public static void main(String[] args) {
        ReadWriteDemo demo = new ReadWriteDemo();
        for (int i = 0; i < 5; i++) {
            final int tempInt = i;
            new Thread(()->{
                demo.put(tempInt+"",tempInt+"");
            }).start();
        }

        for (int i = 0; i < 5; i++) {
            final int tempInt = i;
            new Thread(()->{
                demo.get(tempInt+"");
            }).start();
        }
    }
}
